//
//  CarcircleCommendCell.m
//  CarUser
//
//  Created by 王森林 on 2019/1/28.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "CarcircleCommendCell.h"
#import "CarcircleDetailViewController.h"
@interface CarcircleCommendCell()
@property (nonatomic, strong) NSArray *dataAry;
@property (nonatomic, strong) UIView *bgView1;
@property (nonatomic, strong) UIView *bgView2;
@property (nonatomic, strong) UIView *bgView3;
@property (nonatomic, strong) UIView *bgView4;
@property (nonatomic, assign) NSInteger isZan;

@end

#define ZANTAG 10000
#define VIEWTAG 1000000
@implementation CarcircleCommendCell


- (void)createUIWithData
{
    [self.bgView1 removeAllSubviews];
     [self.bgView2 removeAllSubviews];
     [self.bgView3 removeAllSubviews];
     [self.bgView4 removeAllSubviews];
    [self.contentView addSubview:self.bgView1];
    [self.contentView addSubview:self.bgView2];
    [self.contentView addSubview:self.bgView3];
    [self.contentView addSubview:self.bgView4];
    
    [self.bgView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(15);
        make.height.mas_equalTo(260);
        make.width.mas_equalTo((BOUNDWIDTH-40)/2);
        make.top.mas_equalTo(self.contentView.mas_top).offset(0);
    }];
    
    [self.bgView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.bgView1.mas_right).offset(10);
        make.height.mas_equalTo(210);
        make.width.mas_equalTo((BOUNDWIDTH-40)/2);
        make.top.mas_equalTo(self.contentView.mas_top).offset(0);
    }];
    
    [self.bgView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(15);
        make.height.mas_equalTo(210);
        make.width.mas_equalTo((BOUNDWIDTH-40)/2);
        make.top.mas_equalTo(self.bgView1.mas_bottom).offset(15);
    }];
    
    [self.bgView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.bgView3.mas_right).offset(10);
        make.height.mas_equalTo(260);
        make.width.mas_equalTo((BOUNDWIDTH-40)/2);
        make.top.mas_equalTo(self.bgView2.mas_bottom).offset(15);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-10);
    }];
    
    if (self.dataAry.count > 0) {
        [self createViewWithParentView:self.bgView1 withIndex:0 withData:self.dataAry[0]];
    }
    
    if (self.dataAry.count > 1) {
        [self createViewWithParentView:self.bgView2 withIndex:1 withData:self.dataAry[1]];
    }
    
    if (self.dataAry.count > 2) {
        [self createViewWithParentView:self.bgView3 withIndex:2 withData:self.dataAry[2]];
    }
    if (self.dataAry.count > 3) {
        [self createViewWithParentView:self.bgView4 withIndex:3 withData:self.dataAry[3]];
    }
    
}

- (void)handleTapAction:(UIGestureRecognizer *)gesture
{
    
    NSInteger tag = gesture.view.tag -VIEWTAG;
    NSDictionary *dict  = self.dataAry[tag];

    CarcircleDetailViewController *controller = [[CarcircleDetailViewController alloc] init];
    controller.ID = [dict objectForKey:@"TALK_ID"];
    [[self viewController].navigationController pushViewController:controller animated:YES];
}


- (void)handleZanAction:(id)sender
{
    
    UIButton *zanBtn = sender;
    NSInteger tag = zanBtn.tag -ZANTAG;
    NSDictionary *dict  = self.dataAry[tag];
    
    if (self.isZan == 1) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"您已经点赞～"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
        return;
    }
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"id":[dict objectForKey:@"TALK_ID"],
                             @"TOKEN":user.TOKEN
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CIRCLE_37 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"点赞成功"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
        [zanBtn setImage:IMG(@"zan2") forState:UIControlStateNormal];
        NSInteger num = zanBtn.titleLabel.text.integerValue + 1;
        [zanBtn setTitle:[NSString stringWithFormat:@"%ld",num] forState:UIControlStateNormal];
        self.isZan = 1;
        //        self.zanLabel.text = [NSString stringWithFormat:@"%ld个人点赞",self.zanNum];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
}

- (UIView *)createViewWithParentView:(UIView *)parentView withIndex:(NSInteger)index withData:(NSDictionary *)data
{
    

    UIView *bgView = [UIView new];
    [parentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    bgView.tag = VIEWTAG +index;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAction:)];
    [bgView addGestureRecognizer:tap];
    
    
    UIImageView *imageView = [UIImageView new];
    imageView.layer.cornerRadius = 5;
    imageView.layer.masksToBounds = YES;
    [bgView addSubview:imageView];
    
    NSArray *imgArys = [data objectForKey:@"imageList"];
    if ((imgArys != nil && ![imgArys isKindOfClass:[NSNull class]] && imgArys.count != 0)) {
        NSDictionary *imgDict =imgArys[0];
        [imageView sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [imgDict objectForKey:@"TPLJ00"])] placeholderImage:IMG(@"hot_default")];
    } else{
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = IMG(@"hot_default");
    }
    
    
    if (index ==0 ||index==3) {
        [imageView  mas_makeConstraints:^(MASConstraintMaker *make) {
           (void)make.left.and.right.and.top;
            make.height.mas_equalTo(180);
        }];
    } else {
        [imageView  mas_makeConstraints:^(MASConstraintMaker *make) {
            (void)make.left.and.right.and.top;
            make.height.mas_equalTo(130);
        }];
        
    }
    
    UILabel *titleLbael = [UILabel new];
    titleLbael.font = FONT_SIZE(12);
    titleLbael.textColor = RGB(68, 68, 68);
    titleLbael.numberOfLines = 2;
    NSString * htmlString = [data objectForKey:@"WZNR00"];
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    titleLbael.attributedText = attrStr;
    [bgView addSubview:titleLbael];
    [titleLbael mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imageView.mas_bottom).offset(10);
        make.left.mas_equalTo(bgView.mas_left).offset(0);
        make.right.mas_equalTo(bgView.mas_right).offset(0);
    }];
    
    UIImageView *logoImgv = [[UIImageView alloc]init];
    logoImgv.layer.masksToBounds = YES;
    logoImgv.layer.cornerRadius = 15;
    [logoImgv sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [data objectForKey:@"headIcon"])] placeholderImage:IMG(@"headImage")];
    [bgView addSubview:logoImgv];
    [logoImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(bgView.mas_left).offset(0);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(titleLbael.mas_bottom).offset(5);
    }];
    
    
    UILabel *nicknameLbael = [UILabel new];
    nicknameLbael.font = FONT_SIZE(12);
    nicknameLbael.textColor = RGB(50, 50, 50);
    [bgView addSubview:nicknameLbael];
    nicknameLbael.text = [data objectForKey:@"nickName"];
    [nicknameLbael mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbael.mas_bottom).offset(5);
        make.left.mas_equalTo(logoImgv.mas_right).offset(10);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(12);
    }];

    UIButton *favorBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:IMG(@"zan1") forState:UIControlStateNormal];
        btn.titleLabel.font = FONT_SIZE(10);
        [btn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        btn;
    });
    favorBtn.tag = ZANTAG + index;
    [favorBtn addTarget:self action:@selector(handleZanAction:) forControlEvents:UIControlEventTouchUpInside];
    [favorBtn setTitleEdgeInsets:UIEdgeInsetsMake(0 ,0, 0.0,-15)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
    [favorBtn setImageEdgeInsets:UIEdgeInsetsMake( 0, 0,0.0, 0)];//
    [bgView addSubview:favorBtn];
    [favorBtn setTitle:[NSString stringWithFormat:@"%@",[data objectForKey:@"DZS000"]] forState:UIControlStateNormal];

    [favorBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(bgView.mas_right).offset(-15);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(14);
        make.centerY.mas_equalTo(logoImgv.mas_centerY);
    }];
    
    
  self.isZan = [[data objectForKey:@"DZFLAG"] intValue];
    if (self.isZan == 1) {
        [favorBtn setImage:IMG(@"zan2") forState:UIControlStateNormal];
    } else {
        
        [favorBtn setImage:IMG(@"zan1") forState:UIControlStateNormal];
    }
    
//    NSDictionary *dict = obj;
//    [logoImgv sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [dict objectForKey:@"headIcon"])] placeholderImage:IMG(@"headImage")];
//    titleLab.text = [dict objectForKey:@"nickName"];
//    commentLab.text =  [dict objectForKey:@"PLNR00"];
//    timeLab.text = [dict objectForKey:@"SJ0000"];
//    [favorBtn setTitle:[NSString stringWithFormat:@"%@",[dict objectForKey:@"praise"]] forState:UIControlStateNormal];
    
//
//    logoImgv.frame = CGRectMake(15, 15, 40, 40);
//    logoImgv.layer.masksToBounds = YES;
//    logoImgv.layer.cornerRadius = 20;
//
//    titleLab.frame = CGRectMake(65, 10, BOUNDWIDTH- 80, 20);
//
//    CGSize size = [CommonMethod labWidthFromStr:commentLab.text andFont:commentLab.font andWidth:BOUNDWIDTH -100];
//
//    contentBgView.frame = CGRectMake(65, 35, BOUNDWIDTH - 80, size.height + 20);
//    commentLab.frame = CGRectMake(10, 5, BOUNDWIDTH - 100, size.height + 10);
//    timeLab.frame = CGRectMake(65, contentBgView.size.height + 35+10, 120, 14);
//    favorBtn.frame = CGRectMake(BOUNDWIDTH -45 ,contentBgView.size.height + 35+10 , 30, 14);
//    favorBtn.tag = ZANTAG +idx;
//    [favorBtn addTarget:self action:@selector(handleZanAction:) forControlEvents:UIControlEventTouchUpInside];
//    [favorBtn setTitleEdgeInsets:UIEdgeInsetsMake(0 ,0, 0.0,-15)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
//    [favorBtn setImageEdgeInsets:UIEdgeInsetsMake( 0, 0,0.0, 0)];//
    
    return bgView;
    
}

- (void)setData:(id)data
{
    self.dataAry = [NSArray arrayWithArray:data];
    [self  createUIWithData];
    
}

- (UIView *)bgView1
{
    if (!_bgView1) {
        _bgView1 = [UIView new];
       // _bgView1.backgroundColor = [UIColor redColor];
    }
    return _bgView1;
    
}

- (UIView *)bgView2
{
    if (!_bgView2) {
        _bgView2 = [UIView new];
        // _bgView2.backgroundColor = [UIColor blueColor];
    }
    return _bgView2;
    
}

- (UIView *)bgView3
{
    if (!_bgView3) {
        _bgView3 = [UIView new];
          //_bgView3.backgroundColor = [UIColor yellowColor];
    }
    return _bgView3;
    
}

- (UIView *)bgView4
{
    if (!_bgView4) {
        _bgView4 = [UIView new];
         // _bgView4.backgroundColor = [UIColor redColor];
    }
    return _bgView4;
    
}

//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
//{
//    return 2;
//}
//
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
//{
//    if (section  == 0) {
//        return 3;
//    }
//    return 4;
//}
//
//- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
//    return cell;
//}
//
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
//    return UIEdgeInsetsMake(10, 10, 10, 10);
//}
//
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section ==0) {
//        return CGSizeMake(BOUNDWIDTH-20, arc4random()%100+200);
//    }
//    return CGSizeMake(arc4random()%100+100, arc4random()%100+200);
//}

@end
